package notice

import (
	// "bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"license/pkg/client"
	"log"
	"net/http"
	"net/url"
	"os"
	"time"

	"github.com/robfig/cron"
	gomail "gopkg.in/gomail.v2"
)

type License struct {
    Id int `json:"id,omitempty"`//指定 id
	Custom string `json:"custom,omitempty"` //客户
    Product string `json:"product,omitempty"` //产品
    ExpirDate string `json:"expirDate,omitempty"` //过期时间(支持续签)
    Status string `json:"status,omitempty"` //当前状态(有效/无效)
    PubKey string `json:"pubkey,omitempty"` //公钥
    PrivateKey string `json:"privatekey,omitempty"` //私钥
    IdentificationCode string `json:"identificationcode,omitempty"` //企业识别码
    Ownership string `json:"ownership,omitempty"` //维护人员
    Ipaddress string `json:"ipaddress,omitempty"` //注册IP地址
    Remark string `json:"remark,omitempty"` //备注
    CreateTime string `json:"createTime,omitempty"` //创建时间
    UpdateTime string `json:"updateTime,omitempty"` //更新时间
}

func CheckExpir(){
    log.Println("任务执行时间:", time.Now().Format("2006-01-02 15:04:05"),Mailconfig.Notice.Requesturl)
    req, err := http.NewRequest("GET", Mailconfig.Notice.Requesturl, nil)
	if err != nil {
		log.Println("创建请求失败:", err)
		return
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", Mailconfig.Notice.Token)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Println("发送请求失败:", err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Println("读取响应失败:", err)
		return
	}
    var response map[string]interface{}
	var licenses []License
	err = json.Unmarshal(body, &response)
    if err != nil{
        log.Println(err.Error())
        panic(err.Error())
    }
    code := response["code"].(float64)
    if code == 200{
        log.Println(code)
        data := response["data"].(string)
        err = json.Unmarshal([]byte(data), &licenses)
        if err != nil{
            log.Println(err.Error())
            panic(err.Error())
        }
        for _,key := range licenses{
            Notice_mail(key)
        }
    }else{
        message := response["message"].(string)
        log.Println("查询异常",message)
        return
    }
}

func NoticeApi(key License,content string){
    httpurl := Mailconfig.Notice.Noticeapi
    subject := fmt.Sprintf("客户license到期提醒")
    Method := "POST"
    Authorization := "abcd"
    params := url.Values{}
    params.Set("orgId","88")
    params.Set("subject",subject)
    params.Set("productId","1")
    params.Set("content",content)
    params.Set("to",key.Ownership)
    params.Set("cc",Mailconfig.Notice.Mailcc)
    res := client.HttpCtx(Method,fmt.Sprintf("%s?%s",httpurl,params.Encode()),Authorization,make([]byte, 0))
    log.Println(res)
}

func Notice_mail(key License){
    content := fmt.Sprintf("客户: %s,部署产品: %s,过期时间: %s,请及时登录环境续期",key.Custom,key.Product,key.ExpirDate)
    if Mailconfig.Notice.Noticeapi == ""{
        log.Panicln("邮件方式通知")
        SendMail(key.Ownership,content)
    }else{
        NoticeApi(key,content)
        log.Println("接口方式通知")
    }
}

type Config struct {
	Notice struct {
		Runtime    string `json:"Runtime"` //定时运行时间
        Requesturl string `json:"requesturl"` //请求url地址 http://xxxx/xxx
        Token string `json:"token"`
        Noticeapi string `json:"noticeapi,omitempty"` //接口通知 可以为空
        Mailcc string `json: "mailcc,omitempty"` //邮件抄送
	} `json:"notice"`
    Mail struct {
        Smtphost string `json:"smtphost"`  //邮箱地址
        Port int `json:"port"` //邮箱短裤
        Username string `json:"username"` //邮箱账号
        Password string `json:"password"` //邮箱密码
        From string `json:"from"` //来自地址
    } `json:"mail"`
	Database struct {
		Host     string `json:"host"`
		Port     int    `json:"port"`
		Username string `json:"username"`
		Password string `json:"password"`
		DBName   string `json:"dbname"`
	} `json:"database"`
	Server struct {
		Port    int `json:"port"`
		Timeout int `json:"timeout"`
        Expirdays int `json:"expirdays"`
	} `json:"server"`
}
var Mailconfig Config


func NoticeMail(JsonFile string){
	file, err := os.Open(JsonFile)
	if err != nil {
		log.Println("打开配置文件失败:", err)
		return
	}
	defer file.Close()
	decoder := json.NewDecoder(file)
	err = decoder.Decode(&Mailconfig)
	if err != nil {
		log.Println("解析配置文件失败:", err)
		return
	}
    c := cron.New()
   spec := Mailconfig.Notice.Runtime //获取所配置的定时任务运行时间
   log.Println(spec)
   err = c.AddFunc(spec,CheckExpir)
   if err != nil {
      log.Println("AddFunc error : %v",err)
      panic(err.Error())
   }else{
       log.Println("定时任务添加成功")
   }
   c.Start() //启动
//    defer c.Stop() //暂停
//    time.Sleep(5 * time.Microsecond)
   select {}
}


func SendMail(ownership string,content string){
    msg := gomail.NewMessage()
    msg.SetHeader("From", Mailconfig.Mail.From)
    msg.SetHeader("To", ownership)
    msg.SetHeader("Subject", "License过期提醒")
    msg.SetBody("text/html", content)
    n := gomail.NewDialer(Mailconfig.Mail.Smtphost, Mailconfig.Mail.Port, Mailconfig.Mail.Username, Mailconfig.Mail.Password)
    if err := n.DialAndSend(msg); err != nil {
        panic(err)
    }
    log.Println("发送成功",ownership,content)
    time.Sleep(60)
}